package com.csii.security.authentication.dingtalk;

import com.csii.security.authentication.CustomAuthenticationFailureHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 校验用户输入的手机验证码是否正确
 * @Auther: ian
 */
@Component // 不要少了
public class DingTalkValidateFilter extends OncePerRequestFilter {


    @Autowired
    CustomAuthenticationFailureHandler customAuthenticationFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 1. 判断 是钉钉登录，且post请求
        if("/ding-talk/form".equals(request.getRequestURI())
            && "GET".equalsIgnoreCase(request.getMethod())) {
            try {
                // 校验验证码合法性
                validate(request);
            }catch (AuthenticationException e) {
                // 交给失败处理器进行处理异常
                customAuthenticationFailureHandler.onAuthenticationFailure(request, response, e);
                // 一定要记得结束
                return;
            }
        }

        // 放行
        filterChain.doFilter(request, response);
    }

    private void validate(HttpServletRequest request) {
        /*JSONObject jsb=JSONObject.parseObject(HttpUtil.get("http://vp.csiicloud.com:8001//user/author?dd_token="+request.getParameter("dd_token")));
        JSONObject userJson=jsb.getJSONObject("data");
        if(userJson!=null)
        {
           request.setAttribute("dd_user",userJson);
        }else {
            throw new ValidateCodeException("用户登录失败");
        }*/
    }
}
